﻿using IntoStationSystem.Db;
using IntoStationSystem.Global;
using IntoStationSystem.Models;
using Prism.Mvvm;
using S7.Net;
using System.Collections.ObjectModel;
using System.Threading.Tasks;

namespace IntoStationSystem.ViewModels
{
    public class ResetPartCodeViewModel : BindableBase
    {
        public ResetPartCodeViewModel()
        {
            //DbHelper.Log("ResetPartCodeViewModel");
        }

        public ObservableCollection<ResetPartCodeModel> Resets { get; set; } = new ObservableCollection<ResetPartCodeModel>();
        private HomeViewModel home => Locator.Instance.MainPageVM;

        /// <summary>
        /// 锁
        /// </summary>
        private object locker = new object();

        public void Reset()
        {
            Task.Run(() =>
            {
                lock (locker)
                {
                    Db.DbHelper.ResetPartCode(Resets);
                    foreach (var model in Resets)
                    {
                        if (model.IsReset)
                        {
                            for (int i = 0; i < home.PartCodes.Count; i++)
                            {
                                if (home.PartCodes[i].Contains(model.PartCode))
                                {
                                    home.PartCodes[i] = "";
                                    //home.PartCodes.Remove(model.PartCode);
                                }
                            }
                        }

                    }
                    //解绑写入
                    Locator.Instance.Service.ResetPartWrite();
                }
            });
        }

        public void Load()
        {
            Resets.Clear();
            string repeatCode = Locator.Instance.MainPageVM.RepeatCode;

            for (int i = 0; i < home.PartCodes.Count; i++)
            {
                if (!string.IsNullOrEmpty(home.PartCodes[i]))
                {
                    foreach (var model in Db.DbHelper.LoadPartCodes(home.PartCodes[i]))
                    {
                        Resets.Add(new ResetPartCodeModel()
                        {
                            Index = model.Count,
                            IsReset = model.IsReset,
                            PartCode = model.Code,
                            DateTime = model.DateTime
                        });
                    }
                }

            }
            if (!home.PartCodes.Contains(repeatCode) && !string.IsNullOrEmpty(repeatCode))
            {
                foreach (var model in Db.DbHelper.LoadPartCodes(repeatCode))
                {
                    Resets.Add(new ResetPartCodeModel()
                    {
                        Index = model.Count,
                        IsReset = model.IsReset,
                        PartCode = model.Code,
                        DateTime = model.DateTime
                    });
                }

            }

        }
    }


}
